import requests
import json
from typing import Dict, Any
try:
    from .utils import EnhancedOutput as Debug, OutputType as DebugType
except ImportError:
    from utils import EnhancedOutput as Debug, OutputType as DebugType

class HttpRequestTool:
    name = "http_request"
    description = "发送HTTP请求。支持GET、POST等HTTP方法访问网页或API"
    parameters = {
        "type": "object",
        "properties": {
            "method": {
                "type": "string",
                "description": "HTTP方法 (GET, POST, PUT, DELETE)"
            },
            "url": {
                "type": "string",
                "description": "请求的URL地址"
            },
            "headers": {
                "type": "string",
                "description": "请求头，JSON格式字符串"
            },
            "data": {
                "type": "string",
                "description": "请求数据，JSON格式字符串"
            }
        },
        "required": ["method", "url"]
    }

    def execute(self, args: Dict[str, Any]) -> Dict[str, Any]:
        try:
            method = args["method"].upper()
            url = args["url"]
            
            headers = {}
            data = None
            
            if "headers" in args and args["headers"]:
                try:
                    headers = json.loads(args["headers"])
                except json.JSONDecodeError:
                    return {
                        "success": False,
                        "stdout": "",
                        "stderr": "请求头格式错误，必须是有效的JSON字符串"
                    }
            
            if "data" in args and args["data"]:
                try:
                    data = json.loads(args["data"])
                except json.JSONDecodeError:
                    return {
                        "success": False,
                        "stdout": "",
                        "stderr": "请求数据格式错误，必须是有效的JSON字符串"
                    }
            
            Debug.display(f"发送 {method} 请求到: {url}", DebugType.INFO)
            
            # 发送请求
            if method == "GET":
                response = requests.get(url, headers=headers)
            elif method == "POST":
                response = requests.post(url, headers=headers, json=data)
            elif method == "PUT":
                response = requests.put(url, headers=headers, json=data)
            elif method == "DELETE":
                response = requests.delete(url, headers=headers)
            else:
                return {
                    "success": False,
                    "stdout": "",
                    "stderr": f"不支持的HTTP方法: {method}"
                }
            
            # 构建响应信息
            result = []
            result.append(f"状态码: {response.status_code}")
            result.append(f"响应头: {dict(response.headers)}")
            result.append(f"响应内容:")
            
            try:
                # 尝试格式化JSON响应
                json_data = response.json()
                result.append(json.dumps(json_data, ensure_ascii=False, indent=2))
            except:
                # 如果不是JSON，直接返回文本
                result.append(response.text)
            
            return {
                "success": True,
                "stdout": "\n".join(result),
                "stderr": ""
            }
            
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"HTTP请求失败: {str(e)}"
            }

class WebFetchTool:
    name = "web_fetch"
    description = "获取网页内容。简单获取指定URL的网页文本内容"
    parameters = {
        "type": "object",
        "properties": {
            "url": {
                "type": "string",
                "description": "要获取的网页URL"
            }
        },
        "required": ["url"]
    }

    def execute(self, args: Dict[str, Any]) -> Dict[str, Any]:
        try:
            url = args["url"]
            
            Debug.display(f"获取网页内容: {url}", DebugType.INFO)
            
            response = requests.get(url, timeout=30)
            response.raise_for_status()
            
            return {
                "success": True,
                "stdout": response.text,
                "stderr": ""
            }
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"获取网页失败: {str(e)}"
            }